package fr.unice.client;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.Window.Location;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.RootPanel;
import com.smartgwt.client.data.Criteria;
import com.smartgwt.client.types.Alignment;
import com.smartgwt.client.types.Cursor;
import com.smartgwt.client.types.DragAppearance;
import com.smartgwt.client.types.ListGridEditEvent;
import com.smartgwt.client.types.Side;
import com.smartgwt.client.types.VisibilityMode;
import com.smartgwt.client.util.SC;
import com.smartgwt.client.widgets.HTMLFlow;
import com.smartgwt.client.widgets.IButton;
import com.smartgwt.client.widgets.ImgButton;
import com.smartgwt.client.widgets.Window;
import com.smartgwt.client.widgets.events.ClickEvent;
import com.smartgwt.client.widgets.events.ClickHandler;
import com.smartgwt.client.widgets.events.CloseClientEvent;
import com.smartgwt.client.widgets.events.DoubleClickEvent;
import com.smartgwt.client.widgets.events.DoubleClickHandler;
import com.smartgwt.client.widgets.events.DropEvent;
import com.smartgwt.client.widgets.events.DropHandler;
import com.smartgwt.client.widgets.form.DynamicForm;
import com.smartgwt.client.widgets.form.events.ItemChangedEvent;
import com.smartgwt.client.widgets.form.events.ItemChangedHandler;
import com.smartgwt.client.widgets.form.events.SubmitValuesEvent;
import com.smartgwt.client.widgets.form.events.SubmitValuesHandler;
import com.smartgwt.client.widgets.form.fields.ButtonItem;
import com.smartgwt.client.widgets.form.fields.SelectItem;
import com.smartgwt.client.widgets.form.fields.TextItem;
import com.smartgwt.client.widgets.form.fields.events.KeyPressEvent;
import com.smartgwt.client.widgets.form.fields.events.KeyPressHandler;
import com.smartgwt.client.widgets.grid.ListGrid;
import com.smartgwt.client.widgets.grid.ListGridField;
import com.smartgwt.client.widgets.grid.ListGridRecord;
import com.smartgwt.client.widgets.grid.events.CellClickEvent;
import com.smartgwt.client.widgets.grid.events.CellClickHandler;
import com.smartgwt.client.widgets.grid.events.EditCompleteEvent;
import com.smartgwt.client.widgets.grid.events.EditCompleteHandler;
import com.smartgwt.client.widgets.grid.events.EditorEnterEvent;
import com.smartgwt.client.widgets.grid.events.EditorEnterHandler;
import com.smartgwt.client.widgets.layout.HLayout;
import com.smartgwt.client.widgets.layout.SectionStack;
import com.smartgwt.client.widgets.layout.SectionStackSection;
import com.smartgwt.client.widgets.layout.VLayout;
import com.smartgwt.client.widgets.tab.Tab;
import com.smartgwt.client.widgets.tab.TabSet;
import com.smartgwt.client.widgets.tab.events.CloseClickHandler;
import com.smartgwt.client.widgets.tab.events.TabCloseClickEvent;

import fr.unice.client.services.GtunesService;
import fr.unice.client.services.GtunesServiceAsync;
import fr.unice.client.services.InitializationService;
import fr.unice.client.services.InitializationServiceAsync;
import fr.unice.client.services.PlaylistService;
import fr.unice.client.services.PlaylistServiceAsync;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 * 
 * @author PELLEGRINO Laurent
 * @author TROVATO Alexandre
 * 
 * @version 1.0
 */
public class Gtunes implements EntryPoint {
	/**
	 * The message displayed to the user when the server cannot be reached or
	 * returns an error.
	 */
	private static final String SERVER_ERROR = "An error occurred while "
			+ "attempting to contact the server. Please check your network "
			+ "connection and try again.";

	/**
	 * Creates a remote service proxy to talk to the server-side gtunes service.
	 */
	private final GtunesServiceAsync gtunesService = GWT
			.create(GtunesService.class);

	/**
	 * Creates a remote proxy to talk to the server-side initialization service.
	 */
	private final InitializationServiceAsync initializeService = GWT
			.create(InitializationService.class);

	/**
	 * Creates a remote proxy to talk to the server-side playlist service.
	 */
	private final PlaylistServiceAsync playlistService = GWT
			.create(PlaylistService.class);

	private HLayout toolbar;
	private HLayout container = new HLayout();
	private VLayout pageLeft = new VLayout();
	private VLayout page = new VLayout();
	private SectionStack stackPanel;

	private TabSet tabSet;
	private HashMap<Long, Tab> tabs = new HashMap<Long, Tab>();

	private HashMap<String, AudioFileDTO> audioFiles = new HashMap<String, AudioFileDTO>();

	private ListGrid playlistsGrid = new ListGrid();
	private List<PlaylistDTO> playlists;

	private String oldPlaylistName;

	/**
	 * This is the entry point method.
	 */
	public void onModuleLoad() {
		VLayout global = new VLayout();
		global.setWidth("88%");
		global.setMembersMargin(15);

		this.container.setHeight100();
		this.container.setWidth("100%");
		this.container.setMembersMargin(30);

		this.stackPanel = this.createStackPanel();
		this.toolbar = this.createToolbar();

		this.tabSet = this.createTabSet();

		this.pageLeft.addMember(this.stackPanel);
		this.pageLeft.setWidth(220);
		this.page.addMember(this.tabSet);
		this.page.setWidth("*");
		this.page.setHeight100();

		this.container.addMember(this.pageLeft);
		this.container.addMember(this.page);

		global.addMember(this.toolbar);
		global.addMember(this.container);

		this.loadPlaylists();
		this.loadAudioFiles();

		RootPanel.get("global").add(global);
	}

	private void loadAudioFiles() {
		this.gtunesService
				.getAudioFiles(new AsyncCallback<List<AudioFileDTO>>() {
					public void onFailure(Throwable caught) {
						SC.say(SERVER_ERROR);
					}

					public void onSuccess(List<AudioFileDTO> result) {
						// Store data in a hashmap in order to have better
						// complexity for lookup
						Iterator<AudioFileDTO> it = result.iterator();
						AudioFileDTO current = null;

						while (it.hasNext()) {
							current = it.next();
							Gtunes.this.audioFiles
									.put(current.getId(), current);
						}

						// Update the default tab with all the audio files we
						// receive
						Gtunes.this.updateDefaultTab(result);
					}
				});
	}

	private void loadPlaylists() {
		this.playlistService
				.getPlaylists(new AsyncCallback<List<PlaylistDTO>>() {
					public void onFailure(Throwable caught) {
						SC.say(Gtunes.SERVER_ERROR);
					}

					public void onSuccess(List<PlaylistDTO> result) {
						Gtunes.this.playlists = result;
						Gtunes.this.updatePlaylistsGrid();
					}
				});
	}

	private HLayout createToolbar() {
		HLayout layout = new HLayout();
		layout.setAlign(Alignment.RIGHT);
		layout.setHeight(20);

		final DynamicForm form = new DynamicForm();
		form.setNumCols(3);

		TextItem searchCriteria = new TextItem("criteria");
		searchCriteria.setHeight(20);
		searchCriteria.setTitle("Filter");

		SelectItem searchType = new SelectItem("searchType");
		searchType.setDefaultValue("name");
		searchType.setHeight(20);
		searchType.setShowTitle(false);

		LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();
		map.put("album", "Album");
		map.put("artist", "Artist");
		map.put("genre", "Genre");
		map.put("name", "Name");
		searchType.setValueMap(map);

		form.addItemChangedHandler(new ItemChangedHandler() {
			public void onItemChanged(ItemChangedEvent event) {
				Criteria criteria = new Criteria(form
						.getValueAsString("searchType"), form
						.getValueAsString("criteria"));

				for (Tab tab : Gtunes.this.tabSet.getTabs()) {
					ListGrid grid = (ListGrid) tab.getPane();
					grid.filterData(criteria);
				}
			}
		});

		form.setFields(searchCriteria, searchType);
		layout.addMember(form);

		return layout;
	}

	private TabSet createTabSet() {
		final TabSet tabSet = new TabSet();
		tabSet.setTabBarPosition(Side.TOP);
		tabSet.setTabBarAlign(Side.LEFT);
		tabSet.setWidth("100%");
		tabSet.setHeight(500);
		tabSet.setTabBarThickness(25);
		tabSet.addCloseClickHandler(new CloseClickHandler() {
			public void onCloseClick(TabCloseClickEvent event) {
				Gtunes.this.tabs.remove(new Long(event.getTab().getID()));
				Gtunes.this.tabSet.removeTab(event.getTab());
			}

		});

		Tab defaultTab = new Tab("Avaible Songs", "/images/song.png");
		ListGrid defaultAudioFileGrid = this.createAudioFileListGrid();
		defaultAudioFileGrid.setCanDrag(true);
		defaultAudioFileGrid.setCanDrop(true);
		defaultAudioFileGrid.setCanDragRecordsOut(true);
		defaultAudioFileGrid.setDragType("song");
		defaultAudioFileGrid.setDragAppearance(DragAppearance.TRACKER);
		defaultAudioFileGrid.setCursor(Cursor.MOVE);
		defaultTab.setPane(defaultAudioFileGrid);

		this.tabs.put(new Long(0), defaultTab);
		tabSet.addTab(defaultTab);
		return tabSet;
	}

	private SectionStack createStackPanel() {
		SectionStack sectionStack = new SectionStack();
		sectionStack.setMembersMargin(2);
		sectionStack.setVisibilityMode(VisibilityMode.MULTIPLE);
		sectionStack.setHeight(500);

		// INITIALIZATION SECTION ---------------------

		SectionStackSection initSection = new SectionStackSection(
				"Initialization");
		initSection.setExpanded(false);
		initSection.setCanCollapse(true);

		VLayout layout = new VLayout();
		layout.setAlign(Alignment.CENTER);
		layout.setHeight(100);
		layout.setWidth100();
		layout.setMargin(10);
		layout.setMembersMargin(10);

		IButton initAudioFilesButton = new IButton("Initialize audiofiles");
		initAudioFilesButton.setHeight(20);
		initAudioFilesButton.setWidth(150);
		initAudioFilesButton.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				Gtunes.this.initializeService
						.initAudioFiles(new AsyncCallback<Void>() {
							public void onFailure(Throwable caught) {
								SC.say(Gtunes.SERVER_ERROR);
							}

							public void onSuccess(Void result) {
								Gtunes.this.loadAudioFiles();
								SC
										.say("AudioFiles initialization has succeeded.");
							}
						});
			}
		});

		IButton initPlaylistsButton = new IButton("Initialize   playlists");
		initPlaylistsButton.setHeight(20);
		initPlaylistsButton.setWidth(150);
		initPlaylistsButton.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				Gtunes.this.initializeService
						.initPlaylists(new AsyncCallback<Void>() {
							public void onFailure(Throwable caught) {
								SC.say(Gtunes.SERVER_ERROR);
							}

							public void onSuccess(Void result) {
								Gtunes.this.loadPlaylists();
								SC
										.say("Playlists initialization has succeeded.");
							}
						});
			}
		});

		IButton deleteAllButton = new IButton("Delete all from database");
		deleteAllButton.setHeight(20);
		deleteAllButton.setWidth(180);
		deleteAllButton.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				Gtunes.this.initializeService
						.deleteAll(new AsyncCallback<Void>() {
							public void onFailure(Throwable caught) {
								SC.say(Gtunes.SERVER_ERROR);
							}

							public void onSuccess(Void result) {
								Location.reload();
							}
						});
			}
		});

		layout.addMember(new HTMLFlow("Select the action to perform : "));
		layout.addMember(initAudioFilesButton);
		layout.addMember(initPlaylistsButton);
		layout.addMember(deleteAllButton);
		initSection.addItem(layout);
		sectionStack.addSection(initSection);

		// PLAYLISTS SECTION -----------------

		this.playlistsGrid.setShowAllRecords(true);
		this.playlistsGrid.setCanAcceptDrop(true);
		this.playlistsGrid.setCanAcceptDroppedRecords(true);
		this.playlistsGrid.setCanEdit(true);
		this.playlistsGrid.setDropTypes("song");
		this.playlistsGrid.setCellPadding(5);
		this.playlistsGrid.setCellHeight(22);
		this.playlistsGrid.setSelectOnEdit(false);
		this.playlistsGrid.setAlternateRecordStyles(true);
		this.playlistsGrid.setEditEvent(ListGridEditEvent.DOUBLECLICK);
		this.playlistsGrid.addDropHandler(new DropHandler() {
			public void onDrop(DropEvent event) {
				ListGrid source = (ListGrid) event.getSource();
				final int row = source.getEventRow();

				// Check if we drop on a line of the list grid which contains
				// the playlists
				if (row >= 0) {
					final PlaylistRecord pr = ((PlaylistRecord) Gtunes.this.playlistsGrid
							.getRecord(row));
					Long playlistID = new Long(pr.getId());
					final String audioFileIDToAdd = ((AudioFileRecord) ((ListGrid) Gtunes.this.tabs
							.get(new Long(0)).getPane()).getSelectedRecord())
							.getId();

					Gtunes.this.playlistService.addAudioFileToPlaylist(
							playlistID, audioFileIDToAdd,
							new AsyncCallback<Void>() {
								public void onFailure(Throwable caught) {
									SC.say(SERVER_ERROR);
								}

								public void onSuccess(Void result) {
									// Update the local playlist record
									pr.add(audioFileIDToAdd);
									// Refresh the cell containing the number of
									// audio files for the playlist which has
									// been update
									Gtunes.this.playlistsGrid.refreshCell(row,
											1);
									// Update the tab which is associated with
									// the playlist which has been update (if it
									// is open)
									Tab tabToUpdate = Gtunes.this.tabs.get(pr
											.getId());
									if (tabToUpdate != null) {
										Gtunes.this.updateTab(tabToUpdate, pr
												.getAudioFileIDs());
									}
								}
							});

				}
			}
		});

		this.playlistsGrid.addCellClickHandler(new CellClickHandler() {
			public void onCellClick(CellClickEvent event) {
				PlaylistRecord playlistRecord = (PlaylistRecord) Gtunes.this.playlistsGrid
						.getRecord(event.getRowNum());

				Tab tab = Gtunes.this.tabs.get(playlistRecord.getId());
				if (tab == null) {
					// Creates a new tab for the selected playlist
					Tab newTab = new Tab(playlistRecord.getName());
					newTab.setID("" + playlistRecord.getId());
					newTab.setPane(Gtunes.this.createAudioFileListGrid());
					newTab.setCanClose(true);

					Gtunes.this.tabSet.addTab(newTab);
					Gtunes.this.tabSet.selectTab(newTab);
					Gtunes.this.tabs.put(new Long(playlistRecord.getId()),
							newTab);
					Gtunes.this.updateTab(newTab, playlistRecord
							.getAudioFileIDs());
				} else {
					Gtunes.this.tabSet.selectTab(tab);
				}
			}

		});

		this.playlistsGrid.addEditorEnterHandler(new EditorEnterHandler() {
			public void onEditorEnter(EditorEnterEvent event) {
				Gtunes.this.oldPlaylistName = ((PlaylistRecord) event
						.getRecord()).getName();
			}
		});

		this.playlistsGrid.addEditCompleteHandler(new EditCompleteHandler() {
			public void onEditComplete(EditCompleteEvent event) {
				final PlaylistRecord playlistRecord = (PlaylistRecord) Gtunes.this.playlistsGrid
						.getRecord(event.getRowNum());

				if (playlistRecord.getName() == null) {
					playlistRecord.setName(Gtunes.this.oldPlaylistName);
					SC
							.say("The playlist name cannot be empty. Please enter one.");
				} else if (Gtunes.this.getPlaylistByName(playlistRecord
						.getName()) != null) {
					playlistRecord.setName(Gtunes.this.oldPlaylistName);
					SC
							.say("A playlist with the same name already exist. Please choose an another name.");
				} else {
					Gtunes.this.playlistService.updatePlaylist(playlistRecord
							.getId(), playlistRecord.getName(),
							new AsyncCallback<Void>() {
								public void onFailure(Throwable caught) {
									SC.say(Gtunes.SERVER_ERROR);
								}

								public void onSuccess(Void result) {
									Tab tab = Gtunes.this.tabs
											.get(playlistRecord.getId());
									Gtunes.this.getPlaylistByName(
											Gtunes.this.oldPlaylistName)
											.setName(playlistRecord.getName());
									if (tab != null) {
										Gtunes.this.tabSet.setTabTitle(""
												+ playlistRecord.getId(),
												playlistRecord.getName());
									}
								}
							});
				}
			}

		});

		ListGridField playlistName = new ListGridField("name", "Name");
		playlistName.setCanEdit(true);
		playlistName.setIcon("/images/disk.png");

		ListGridField playlistNbSong = new ListGridField("nbAudioFiles",
				"Nb song");
		playlistNbSong.setAlign(Alignment.CENTER);
		playlistNbSong.setDefaultValue(0f);
		playlistNbSong.setCanEdit(false);
		playlistNbSong.setWidth(60);

		this.playlistsGrid.setEditByCell(true);
		this.playlistsGrid.setFields(playlistName, playlistNbSong);

		ImgButton addButton = new ImgButton();
		addButton.setSrc("[SKIN]actions/add.png");
		addButton.setSize(16);
		addButton.setShowFocused(false);
		addButton.setShowRollOver(false);
		addButton.setShowDown(false);
		addButton.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				final Window winModal = new Window();
				winModal.setWidth(340);
				winModal.setTitle("New Playlist");
				winModal.setShowMinimizeButton(false);
				winModal.setIsModal(true);
				winModal.centerInPage();

				final DynamicForm form = new DynamicForm();
				form.setAutoFocus(true);
				form.setPadding(20);
				form.setNumCols(3);
				form.addSubmitValuesHandler(new SubmitValuesHandler() {
					public void onSubmitValues(SubmitValuesEvent event) {
						Gtunes.this.addPlaylist(form
								.getValueAsString("playlistName"));
					}

				});

				final TextItem playlistNameTextItem = new TextItem(
						"playlistName");
				playlistNameTextItem.setHeight(20);
				playlistNameTextItem.setTitle("Name");
				playlistNameTextItem.setWrapTitle(false);
				playlistNameTextItem.addKeyPressHandler(new KeyPressHandler() {
					public void onKeyPress(KeyPressEvent event) {
						if (event.getKeyName().equals("Enter")) {
							form.submit();
							winModal.destroy();
						}
					}
				});

				ButtonItem createPlaylistButton = new ButtonItem("Create");
				createPlaylistButton.setStartRow(false);
				createPlaylistButton.setHeight(20);
				createPlaylistButton
						.addClickHandler(new com.smartgwt.client.widgets.form.fields.events.ClickHandler() {
							public void onClick(
									com.smartgwt.client.widgets.form.fields.events.ClickEvent event) {
								form.submit();
								winModal.destroy();
							}
						});

				form.setFields(playlistNameTextItem, createPlaylistButton);
				winModal.addItem(form);
				winModal.show();
			}
		});

		ImgButton removeButton = new ImgButton();
		removeButton.setSrc("[SKIN]actions/remove.png");
		removeButton.setSize(16);
		removeButton.setShowFocused(false);
		removeButton.setShowRollOver(false);
		removeButton.setShowDown(false);
		removeButton.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				final Long playlistId = ((PlaylistRecord) Gtunes.this.playlistsGrid
						.getSelectedRecord()).getId();
				Gtunes.this.playlistService.removePlaylist(playlistId,
						new AsyncCallback<Void>() {
							public void onFailure(Throwable caught) {
								SC.say(Gtunes.SERVER_ERROR);
							}

							public void onSuccess(Void result) {
								PlaylistRecord p = (PlaylistRecord) Gtunes.this.playlistsGrid
										.getSelectedRecord();
								Gtunes.this.playlistsGrid.removeData(p);

								Tab tab = Gtunes.this.tabs.get(playlistId);
								if (tab != null) {
									Gtunes.this.tabs.remove(playlistId);
									Gtunes.this.tabSet.removeTab(tab);
								}
							}
						});
			}
		});

		SectionStackSection playlistSection = new SectionStackSection(
				"Playlists");
		playlistSection.setExpanded(true);
		playlistSection.setCanCollapse(false);
		playlistSection.addItem(this.playlistsGrid);
		playlistSection.setControls(addButton, removeButton);
		sectionStack.addSection(playlistSection);

		return sectionStack;
	}

	private ListGrid createAudioFileListGrid() {
		final ListGrid audioFileGrid = new ListGrid();
		audioFileGrid.setAutoHeight();
		audioFileGrid.setAlternateRecordStyles(true);
		audioFileGrid.setCellHeight(25);
		audioFileGrid.setEmptyCellValue("unknown");
		audioFileGrid.setEmptyMessage("<br/> No song avaible.");
		audioFileGrid.setHeight("100%");
		audioFileGrid.setWidth("100%");
		audioFileGrid.setCellPadding(5);
		audioFileGrid.setDataSource(new AudioFileDS());
		audioFileGrid.setAutoFetchData(true);
		audioFileGrid.addDoubleClickHandler(new DoubleClickHandler() {

			public void onDoubleClick(DoubleClickEvent event) {

				AudioFileRecord audioFile = (AudioFileRecord) audioFileGrid
						.getSelectedRecord();

				final Window window = new Window();
				window.setTitle(audioFile.getName());
				window.setWidth(250);
				window.setIsModal(true);
				window.setHeight(80);
				window.setCanDragReposition(true);
				window.setCanDragResize(true);
				window.centerInPage();

				String buf = "";
				buf += "<div id=\"dewplayer_content\">";
				buf += "<object classid=\"clsid:d27cdb6e-ae6d-11cf-96b8-444553540000\" codebase=\"http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,0,0\" width=\"200\" height=\"20\" id=\"dewplayer\" align=\"middle\">";
				buf += "<param name=\"allowScriptAccess\" value=\"sameDomain\" />";
				buf += "<param name=\"movie\" value=\"/dewplayer.swf?mp3="
						+ audioFile.getURI() + "\" />";
				buf += "<param name=\"quality\" value=\"high\" />";
				buf += "<param name=\"bgcolor\" value=\"#ffffff\" />";
				buf += "<param name=\"wmode\" value=\"transparent\" />";
				buf += "<embed src=\"/dewplayer.swf?mp3="
						+ audioFile.getURI()
						+ "\" wmode=\"transparent\" quality=\"high\" bgcolor=\"#ffffff\" width=\"200\" height=\"20\" name=\"dewplayer\" align=\"middle\" allowScriptAccess=\"sameDomain\" type=\"application/x-shockwave-flash\" pluginspage=\"http://www.macromedia.com/go/getflashplayer\" />";
				buf += "</object>";
				buf += "</div>";

				final HTMLFlow html = new HTMLFlow(buf);

				html.setMargin(15);
				window.addItem(html);
				window
						.addCloseClickHandler(new com.smartgwt.client.widgets.events.CloseClickHandler() {

							public void onCloseClick(CloseClientEvent event) {
								html.destroy();
								window.destroy();
							}

						});
				window.show();

			}

		});

		final ListGridField nameField = new ListGridField("name", "Name");
		final ListGridField timeField = new ListGridField("duration", "Time");
		timeField.setWidth("11%");
		timeField.setAlign(Alignment.CENTER);
		final ListGridField artistField = new ListGridField("artist", "Artist");
		artistField.setWidth("20%");
		final ListGridField albumField = new ListGridField("album", "Album");
		albumField.setWidth("29%");
		final ListGridField genreField = new ListGridField("genre", "Genre");
		genreField.setWidth("20%");

		audioFileGrid.setFields(nameField, timeField, artistField, albumField,
				genreField);
		audioFileGrid.setCanResizeFields(true);

		return audioFileGrid;
	}

	private void updatePlaylistsGrid() {
		ListGridRecord[] playlistRecords = new ListGridRecord[this.playlists
				.size()];

		int i = 0;
		for (PlaylistDTO playlistDTO : this.playlists) {
			playlistRecords[i] = new PlaylistRecord(playlistDTO.getId(),
					playlistDTO.getName(), playlistDTO.getNbAudioFiles(),
					(ArrayList<String>) playlistDTO.getAudioFileIDs());
			i++;
		}

		this.playlistsGrid.setData(playlistRecords);
	}

	private PlaylistDTO getPlaylistByName(String name) {
		for (PlaylistDTO playlistDTO : this.playlists) {
			if (playlistDTO.getName().equals(name)) {
				return playlistDTO;
			}
		}

		return null;
	}

	private boolean contains(PlaylistRecord playlistRecord,
			String audioFileIDToAdd) {
		for (String audioFileID : playlistRecord.getAudioFileIDs()) {
			SC.say("ad = " + audioFileID);
			if (audioFileID.equals(audioFileIDToAdd)) {
				return true;
			}
		}
		SC.say("false");
		return false;
	}

	private void updateTab(Tab tab, ArrayList<String> audioFileIDs) {
		ArrayList<AudioFileDTO> audioFilesDTO = new ArrayList<AudioFileDTO>();
		ListGrid listGrid = ((ListGrid) tab.getPane());

		for (String audioFileID : audioFileIDs) {
			audioFilesDTO.add(this.audioFiles.get(audioFileID));
		}

		((AudioFileDS) listGrid.getDataSource()).addAll(audioFilesDTO);
	}

	private void updateDefaultTab(List<AudioFileDTO> audioFilesDTO) {
		Tab defaultTab = this.tabs.get(new Long(0));
		ListGrid listGrid = ((ListGrid) defaultTab.getPane());

		((AudioFileDS) listGrid.getDataSource()).addAll(audioFilesDTO);
	}

	private void addPlaylist(final String name) {
		if (name == null) {
			SC.say("Information", "The playlist name is compulsory !");
		} else {

			if (this.getPlaylistByName(name) != null) {
				SC
						.say("Information",
								"A playlist with the same name already exist. Please choose an another.");
			} else {
				Gtunes.this.playlistService.addPlaylist(name,
						new AsyncCallback<Long>() {
							public void onFailure(Throwable caught) {
								SC.say(Gtunes.SERVER_ERROR);
							}

							public void onSuccess(Long result) {
								Playlist p = new Playlist(name);
								p.setId(result);
								PlaylistDTO pdto = new PlaylistDTO(name);
								pdto.setId(result);
								Gtunes.this.playlists.add(pdto);
								Gtunes.this.updatePlaylistsGrid();
							}
						});
			}

		}
	}
}
